<?php
include_once 'application/application.php';




class Page_reason {



    public $action;
    public $error;



    public function __construct() {
        $this->action = Arr::getValue($_POST, 'action', false);

        DB::connect();
        if (!DB::state()) {
            $this->error = DB::getError();
        }
    }

    public function __destruct() {

    }
    
    
    
    
    
    
    function fillData () {
        //if (!ConceptionsCollection::Init())   $this->error = 'Проблемы со списком концепций';
        
        $allviews = getAllViews();
        $vviews = selectViewableObjectsFromSet($allviews);
        if (!sortViewsByName($vviews)) {
            $vviews = array();
            $this->error = "Ошибка в списке отображений";
        }
        
        $params = array(
            'allviews' => $allviews,
            'visviews' => $vviews,
            //'cities' => getAllCities(),
            //'vgroups' => getAllViewsGroups(),
            //'conceptions' => ConceptionsCollection::allRowsById(),
            //'types' => getObjTypes(),
            //'btypes' => getBuildTypes(),
            //'datatypes' => getDataTypes(),
            'error' => $this->error
        );
        
        /*
        $q = "  SELECT fl.view_id, ds.tbl 
                FROM 
                    {$this->tablefloors} fl, 
                    {$this->tablesen} ds
                WHERE fl.id = ds.floor_id";
        $res = DB::query($q);
        $tables = array();            
        if (DB::$lastReqState)  {
            while ($row = $res->fetch_assoc()) {
                $vid = Arr::getValue($row, 'view_id', FALSE);
                $tbl = Arr::getValue($row, 'tbl', FALSE);
                if ($vid) {
                    if (!Arr::getValue($tables, $vid)) $tables[$vid] = array();
                    if (!in_array($tbl, $tables[$vid])) $tables[$vid][] = $tbl;
                }
            }
        }     
        $alles['tables'] = $tables;
        */
        

        return $params;
    }


    public function addOrUpdate() {
        $J = new JSON();
        if (!Auth::isLogged()) return $J->error('not_logged');
        
        $params = array();
        $action                 = $J->readVar('action');
        $params['id']           = $J->readVar('id');
        $params['to_date']      = mysql_escape_string($J->readVar('to_date'));
        $params['trc_id']       = (int)$J->readVar('trc_id');
        $params['manual_value'] = (float)$J->readVar('manual_value');
        $params['reason']       = mysql_escape_string($J->readVar('reason'));

        
        $res = DB::query("SELECT id FROM `views_fails` WHERE trc_id = {$params['trc_id']} AND DATE(to_date) = DATE('{$params['to_date']}')");
        if (!$res || !DB::state()) return $J->error('Ошибка при работе с базой данных');
        
        
        if ($action == ACTIONS::REASON_ADD) {
            if ($params['id']) return $J->error('Ошибка данных запроса');
            if ($res->num_rows) return $J->error('Запись уже существует. Перезагрузите страницу.');
        }
            
        else if ($action == ACTIONS::REASON_UPD) {
            if (!$params['id']) return $J->error('Ошибка данных запроса');
            if ($res->num_rows) {
                $row = $res->fetch_assoc();
                if ($params['id'] != Arr::getValue($row, 'id', FALSE)) return $J->error('Запись не найдена. Перезагрузите страницу.');
            }
            else return $J->error('Запись не найдена. Перезагрузите страницу.');
        }

        $robj = new Reason($params);
        $JS = $robj->save();
        if (!$JS->getState()) {
            $J->error($JS->getErrorString());
            return $J;
        }

        $J->insertedId = $robj->id;
        return $J;
    }



    public function outPage() {
        $params = $this->fillData();//array();

        $this->printOut(includeFile(APP_PAGE_PARTS.'page_reasons.php', $params));
    }


    
    
    public function itemList() {
        $J = new JSON();
        if (!Auth::isLogged()) return $J->error('not_logged');
        
        $J->readVar('action');
        $from_date  = $J->readVar('from_date');
        $to_date    = $J->readVar('to_date');
        $trc_id     = (int)$J->readVar('trc_id', 0);
        
        $JR = Reason::getFilteredItems($trc_id, $from_date, $to_date);
        if (!$JR->getState()) return $J->error ($JR->getErrorString ());
        
        $J->items = $JR->items;
        return $J;
    }

    public function itemSearch() {
        $J = new JSON();
        if (!Auth::isLogged()) return $J->error('not_logged');
        
        $J->readVar('action');
        $to_date    = $J->readVar('to_date');
        $trc_id     = (int)$J->readVar('trc_id', 0);
        
        $views = getAllViews();
        $v = Arr::getValue($views, $trc_id, false);
        if (!$v) return $J->error ('Не найдено отображение');
        
        
        $JR = Reason::getFilteredItems($trc_id, $to_date, $to_date);
        if (!$JR->getState()) return $J->error ($JR->getErrorString ());
        
        $items = $JR->items;
        $sorted = Arr::getValue($items, 'sorted', array());
        
        if (count($sorted)) $item = $sorted[0];
        else {
            $itemObj = new Reason(array(
                'to_date' => $to_date,
                'trc_id' => $trc_id
            ));
            
            $item = $itemObj->asArray();
            $item['address'] = Arr::getValue($v, 'address', '');
            $item['obj_name'] = Arr::getValue($v, 'obj_name', '');
        }
        
        
        
        
        $J->item = $item;
        return $J;
    }

    
    
    public function itemDelete() {
        $J = new JSON();
        if (!Auth::isLogged()) return $J->error('not_logged');
        
        $J->readVar('action');
        $id     = (int)$J->readVar('id', 0);
        
        if (!$id) return $J->error('Ошибочный запрос');
        
        $res = DB::query("DELETE FROM `views_fails` WHERE id = $id");
        if (!DB::$lastReqState) return $J->error('Ошибка при выполнении операции <!--'.DB::getError().'-->');
        
        $J->state = 1;
        return $J;
    }



    public function printOut( $content = '' ) {

        include_once APP_PAGE_PARTS.'header.php';
        echo Navbar::getHorisontalBar();
        echo Auth::loginForm(true);

        $params = array(
            'leftmenu'  => Navbar::getVerticalBar('leftmenu'),//includeFile(APP_PAGE_PARTS.'leftmenu.php'),
            'content'   => $content? $content : ''
        );
        include APP_PAGE_PARTS.'columns.php';

        include_once APP_PAGE_PARTS.'footer.php';
        die();
    }



}

$page = new Page_reason();

Navbar::$expanded = 'lm-sys-web';
        

if ($page->action) {
    if ($page->action == ACTIONS::REASON_ADD) echo $page->addOrUpdate();
    if ($page->action == ACTIONS::REASON_UPD) echo $page->addOrUpdate();
    if ($page->action == ACTIONS::REASON_LIST) echo $page->itemList();
    if ($page->action == ACTIONS::REASON_SEARCH) echo $page->itemSearch();
    if ($page->action == ACTIONS::REASON_DEL) echo $page->itemDelete();
}
else  {
    if (!Auth::isLogged()) reLocate ('index.php');
    
    Navbar::$active = 'list_reasons';
    $page->outPage();
}
?>